extends Control

const PlayerStats = preload("res://scripts/player/player_stats.gd")

# 声明变量
var skill_dependencies = {}
var skill_costs = {}
var learned_skills = []
var player_stats = null

func _ready():
	# 获取玩家的 stats 实例
	var player = get_tree().get_first_node_in_group("player")
	if player:
		player_stats = player.get_stats()
	else:
		print("错误：找不到玩家节点")
		return
		
	# 初始化技能树
	initialize_skill_tree()
	
	# 连接信号
	for button in get_tree().get_nodes_in_group("skill_buttons"):
		button.pressed.connect(_on_skill_button_pressed.bind(button))
		
	# 更新已学习技能的显示
	update_learned_skills_display()

func initialize_skill_tree():
	# 这里可以从配置文件或其他地方加载技能树数据
	# 暂时使用硬编码的方式
	
	# 设置技能之间的依赖关系
	skill_dependencies = {
		"basic_attack": [],
		"double_jump": ["basic_attack"],
		"dash": ["basic_attack"],
		"heavy_attack": ["basic_attack"],
		"air_attack": ["double_jump"],
		"counter": ["dash"],
		"combo_attack": ["heavy_attack"],
		"ultimate": ["air_attack", "counter", "combo_attack"]
	}
	
	# 设置技能的花费
	skill_costs = {
		"basic_attack": 0,  # 基础技能，默认已解锁
		"double_jump": 1,
		"dash": 1,
		"heavy_attack": 1,
		"air_attack": 2,
		"counter": 2,
		"combo_attack": 2,
		"ultimate": 3
	}
	
	# 初始化已学习的技能
	learned_skills = ["basic_attack"]  # 基础攻击默认已学习
	
	# 更新已学习技能的显示
	update_learned_skills_display()

func update_learned_skills_display():
	# 更新所有技能按钮的显示状态
	for skill_id in skill_dependencies.keys():
		var button = get_node("SkillContainer/" + skill_id)
		if button:
			if skill_id in learned_skills:
				# 已学习的技能显示为激活状态
				button.modulate = Color(0.2, 1.0, 0.2)  # 绿色
				button.text = skill_id + " ✓"
			else:
				# 检查是否可以学习
				var can_learn = true
				for dependency in skill_dependencies[skill_id]:
					if not dependency in learned_skills:
						can_learn = false
						break
				
				if can_learn:
					button.modulate = Color(1.0, 1.0, 1.0)  # 白色，可学习
				else:
					button.modulate = Color(0.5, 0.5, 0.5)  # 灰色，不可学习

func _on_skill_button_pressed(button):
	var skill_id = button.name
	
	# 检查技能是否已经学习
	if skill_id in learned_skills:
		print("技能已经学习过了")
		return
	
	# 检查依赖技能是否已学习
	for dependency in skill_dependencies[skill_id]:
		if not dependency in learned_skills:
			print("需要先学习依赖技能: ", dependency)
			return
	
	# 检查玩家等级是否足够
	if player_stats.level < skill_costs[skill_id]:
		print("等级不足，需要 ", skill_costs[skill_id], " 级")
		return
	
	# 学习技能
	if player_stats.learn_skill(skill_id):
		learned_skills.append(skill_id)
		print("学习了技能: ", skill_id)
		
		# 更新技能点显示
		$SkillPointsLabel.text = "等级: " + str(player_stats.level)
		
		# 更新已学习技能的显示
		update_learned_skills_display()
	else:
		print("学习技能失败")
		
	# 不再需要设置特定的技能属性，因为这些属性在 PlayerStats 中不存在
	# 所有技能逻辑应该在 PlayerStats.learn_skill 中处理 
